package com.apexsoft.test.sample.ams.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apex.ams.annotation.AmsBlockingStub;
import com.apex.ams.util.AasCommService;
import com.apexsoft.aas.service.model.ARequest;
import com.apexsoft.aas.service.model.AResponse;
import com.apexsoft.test.sample.helloworld.HelloRequest;
import com.apexsoft.test.sample.helloworld.HelloResponse;
import com.apexsoft.test.sample.helloworld.HelloworldServiceGrpc;
import com.google.protobuf.util.JsonFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @Author: initializr
 * @Description:
 * @Date: Created in 2019-10-23 13:43
 * @MODIFIED BY:
 */
@Service
public class AmsClientDemo {

    private static final Logger log = LoggerFactory.getLogger(AmsClientDemo.class);

    @AmsBlockingStub
    //@AmsNamespace("${example.ams.namespace:bss}")
    private HelloworldServiceGrpc.HelloworldServiceBlockingStub stub;

    public AResponse aServiceCall(){
        ARequest req = new ARequest();

        req.setParams(new HashMap<String,Object>(){
            {
                put("name","lucy");
            }
        });
        AResponse resp = AasCommService.sendRequest(null,"com.apexsoft.test.sample.service1",req);
        return resp;
    }

    public JSONObject grpcSay(){
        try {
            HelloRequest req = HelloRequest.newBuilder()
                    .setFunc("function")
                    .setHeader("{'token':'aaaaaaaaa'}")
                    .setBody("{'name':'应用架构研发'}")
                    .build();
            HelloResponse resp = stub.say(req);
            return JSON.parseObject(JsonFormat.printer().print(resp));
        }catch(Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            JSONObject result = new JSONObject();
            result.put("code",-1);
            result.put("note",e.getMessage());
            return result;
        }

    }
}
